from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from home import models, homeser
from rest_framework.generics import ListAPIView
from django.core.cache import cache
# Create your views here.
#测试方法
class Topnav(APIView):
    def get(self, request):
        top=models.NavModel.objects.filter(position=True,isshow=True).order_by("order")
        ser=homeser.NavSerializer(top, many=True)
        return Response({"msg":"success","data":ser.data,"code":200})

class Footnav(APIView):
    def get(self, request):
        #先设置一个缓存的key
        key="footnav"
        #判断缓存中是否存在这个key
        cacheres=cache.get(key)
        if cacheres:
            return Response({"msg":"success","data":cacheres,"code":200})
        top=models.NavModel.objects.filter(position=False,isshow=True).order_by("order")
        ser=homeser.NavSerializer(top, many=True)
        cache.set(key,ser.data,60*60*24)
        return Response({"msg":"success","data":ser.data,"code":200})

#轮播图数据
class Banner(APIView):
    def get(self, request):
        banner=models.BannerModel.objects.filter(isshow=True).order_by("order")
        ser = homeser.BannerSerializer(banner, many=True)
        return Response({"msg": "success", "data": ser.data, "code": 200})

class BannerList(ListAPIView):
    queryset = models.BannerModel.objects.filter(isshow=True).order_by("order")
    serializer_class = homeser.BannerSerializer
    def list(self,request, *args, **kwargs):
        queryset=self.get_queryset()
        ser=self.get_serializer(queryset,many=True)
        return Response({"msg": "success", "data": ser.data, "code": 200})
